import os
import re
import moth
import urllib2
from operator import itemgetter
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

api = moth.API("https://api.facebook.com/")
graphApi = moth.API("https://graph.facebook.com/")
endSlash = re.compile('/$')

def getTopTenLiked(accessToken):
	photoToLikes = getPhotoLikes(accessToken)
	filteredList = list(reversed(sorted(photoToLikes.items(),key=itemgetter(1),reverse=True)[:10]))
	returnableList = {}
	for item in filteredList:
		photo = graphApi.get(str(item[0])+"?access_token="+accessToken)
		returnableList[photo[u'source']] = item[1]
	return list(reversed(sorted(returnableList.items(), key=itemgetter(1), reverse=True)[:10]))

def getTopTenCommented(accessToken):
	photoToComments = getPhotoComments(accessToken)
	filteredList = list(reversed(sorted(photoToComments.items(),key=itemgetter(1),reverse=True)[:10]))
	returnableList = {}
	for item in filteredList:
		photo = graphApi.get(str(item[0])+"?access_token="+accessToken)
		returnableList[photo[u'source']] = item[1]
	return list(reversed(sorted(returnableList.items(),key=itemgetter(1),reverse=True)[:10]))

def getPhotoLikes(accessToken):
	photoToLikes = {}
	query = "select user_id,object_id from like where object_id in (select object_id from photo where aid in (select aid from album where owner=me())LIMIT 10000)LIMIT 10000"
	query = urllib2.quote(query)
	dataItems = api.get(buildUrl(query,accessToken))
	for dataItem in dataItems:
		if dataItem[u'object_id'] in photoToLikes:
			photoToLikes[dataItem[u'object_id']] += 1
		else:
			photoToLikes[dataItem[u'object_id']] = 1
	return photoToLikes	

def getPhotoComments(accessToken):
	photoToComments = {}
	query = "select text,object_id from comment where object_id in (select object_id from photo where aid in (select aid from album where owner=me())LIMIT 10000)LIMIT 10000"
	query = urllib2.quote(query)
	dataItems = api.get(buildUrl(query,accessToken))
	for dataItem in dataItems:
		if dataItem[u'object_id'] in photoToComments:
			photoToComments[dataItem[u'object_id']] += 1
		else:
			photoToComments[dataItem[u'object_id']] = 1
	return photoToComments
			
def buildUrl(uri,accessToken=None):
	url="method/fql.query?query="+uri+"&format=json"
	if accessToken:
		url += "&access_token="+accessToken
	return url

class MontageModel(db.Model):
	type = db.StringProperty(required=True, choices=set(["likes","comments"]))
	urlList = db.StringListProperty(required=True)
	countList = db.StringListProperty(required=True)

class MainPage(webapp.RequestHandler):
	def get(self):
		template_values = {}
		path = os.path.join(os.path.dirname(__file__),'index.html')
		self.response.out.write(template.render(path,template_values))

class Builder(webapp.RequestHandler):
	def get(self):
		accessToken = self.request.get('accessToken')
		montageType = self.request.get('type')
		photoList = []
		if montageType == 'comments':
			photoList = getTopTenCommented(accessToken)
		else:
			photoList = getTopTenLiked(accessToken)
		
		montage = MontageModel(type=montageType,urlList=[],countList=[])
		map(lambda x:montage.urlList.append(x[0]),photoList)
		map(lambda x:montage.countList.append(str(x[1])),photoList)
		montage.put()
		
		templateValues = {
			'type' : montageType,
			'photos' : photoList,
			'url' : 'http://mon-tagger.appspot.com/montage?key='+str(montage.key())
		}
		path = os.path.join(os.path.dirname(__file__),'montage.html')
		self.response.out.write(template.render(path,templateValues))

class BuildFromKey(webapp.RequestHandler):
	def get(self):
		montageKey = self.request.get('key')
		montage = db.get(montageKey)
		photoList = []
		for x in range(len(montage.urlList)):
			photoList.append((montage.urlList[x],montage.countList[x]))
		templateValues = {
			'type' : montage.type,
			'photos' : photoList,
			'url' : 'http://mon-tagger.appspot.com/montage?key='+str(montage.key())
		}
		path = os.path.join(os.path.dirname(__file__),'montage.html')
		self.response.out.write(template.render(path,templateValues))
		
application = webapp.WSGIApplication(
	[('/',MainPage),
	('/buildMontage',Builder),
	('/montage',BuildFromKey)
	],debug=True)
	
def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

